<template>
  <div>
    <h1>WebSocket</h1>
    <div v-for="item in reponseData" :key="item.id">
      {{ item }}
    </div>
    <h2 v-if="testnull !== null && testnull">11</h2>
    <h2 v-else>22</h2>
    <h2>当前等待的请求 {{ httpStore.getPendingNum() }}</h2>
    <h2>请求总数 {{ httpStore.getRequestSum() }}</h2>
    <button @click="testHttp">发送请求获取数据</button>
    <button @click="clearData">清空数据</button>
    <button @click="testWebSocket">切换websocket聊天室</button>
    <button @click="testWebSocketClose">关闭websocket</button>
    <button @click="sendMessageForChat">发送websocket数据</button>
  </div>

</template>

<script setup>
import { ref,getCurrentInstance , onUnmounted} from 'vue'
import useHttpStore from '../stores/http/index.js'
const httpStore = useHttpStore()
const { proxy } = getCurrentInstance()
const testnull = ref(true)
const testnull2 = ref(false)
const reponseData = ref([])

proxy.$websocket.initWebSocket()

//发送http请求
const testHttp =()=>{
  console.log(httpStore.getPendingNum())
  proxy.$http.getTableData().then(res => {
    reponseData.value.push(res)
  })
}

//清空数据
const clearData =()=>{
  reponseData.value = []
}

//切换websocket聊天室
const testWebSocket =()=>{
  console.log('切换websocket')
  console.log(proxy.$websocket)
  proxy.$websocket.send({
    type:'sendMessage', //发送类型
    data:{
      message:'hello',
    }
  })
}

//关闭websocket
const testWebSocketClose=()=>{
  console.log('关闭websocket')
  console.log(proxy.$websocket)
  proxy.$websocket.close()
}

//发送websocket数据
const sendMessageForChat=()=>{  
  proxy.$websocket.send({
    url:'/ws/chat', //切换url
    type:'sendMessage', //发送类型
    data:{
      message:'hello',
    }
  })
}

onUnmounted(() => {
  console.log('组件卸载，自动清理资源')
  
  // 清理WebSocket连接
  if (proxy.$websocket) {
    proxy.$websocket.close()
  }
  
  // 清理定时器（如果有的话）
  // clearInterval(timerId)
  
  // 清理事件监听器（如果有的话）
  // window.removeEventListener('resize', handleResize)
  
  console.log('组件卸载完成')
})


</script>